import { DateUtil } from "@/engine/util/DateUtil";
import { LocalStorage } from "@/engine/util/LocalStorage";
import { Logger } from "@/engine/util/Logger";

const UserLocalKey: string = "UserLocalKey"

export class UserModel {

    public static instance: UserModel = new UserModel();

    public static UserStatus = {
        Normal: 0,
        Disable: 1,
    }


    public id: number;
    public userName: string = ""
    public pass: string = ""
    public token: string = ""
    public lastLoginTime: number;

    public init() {
        let str: string = LocalStorage.getItem(UserLocalKey);
        try {
            let obj: object = JSON.parse(str);
            UserModel.instance.id = obj["id"]
            UserModel.instance.userName = obj["userName"];
            UserModel.instance.pass = obj["pass"];
            UserModel.instance.lastLoginTime = obj["lastLoginTime"]
            UserModel.instance.token = obj["token"]
        } catch (error) {

        }
        Logger.log("UserModel.init===", str, UserModel.instance);
    }

    public login(userName: string, pass: string) {
        this.userName = userName;
        this.pass = pass;
        this.lastLoginTime = DateUtil.now();
        this.saveToLocal();
    }

    public logout() {
        this.userName = "";
        this.pass = "";
        this.lastLoginTime = 0
        this.token = ""
        this.saveToLocal()
    }

    public static needShowLogin() {
        if (UserModel.instance.token && (DateUtil.now() - UserModel.instance.lastLoginTime <= 1000 * 60 * 60)) {
            return false
        }
        return true;
    }

    private saveToLocal() {
        let str: string = JSON.stringify(UserModel.instance);
        Logger.log("UserModel.saveToLocal=", str)
        LocalStorage.setItem(UserLocalKey, str);
    }
}